package cn.zhqr.manage.config;

import cn.zhqr.common.config.GlobalConfig;
import cn.zhqr.common.config.GlobalConstants;
import cn.zhqr.common.external.jfinal.MyJsonFactory;
import cn.zhqr.common.util.io.PropUtil;
import cn.zhqr.core.interceptor.CorsInterceptor;
import cn.zhqr.core.interceptor.PermInterceptor;
import cn.zhqr.core.interceptor.PreventRepeatSubmissionInterceptor;
import cn.zhqr.core.interceptor.UncaughtExceptionInterceptor;
import cn.zhqr.manage.interceptor.ManageLoginInterceptor;
import cn.zhqr.mqtt.MqttAsyncClientKit;
import cn.zhqr.mqtt.MqttClientKit;
import com.jfinal.config.*;
import com.jfinal.core.JFinal;
import com.jfinal.ext.plugin.mongo.MongoPlugin;
import com.jfinal.ext.plugin.quartz.QuartzPlugin;
import com.jfinal.ext.plugin.redis.RedisStringSerializer;
import com.jfinal.ext.plugin.tablebind.AutoTableBindPlugin;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.template.Engine;
import redis.clients.jedis.Protocol;

/**
 * Created by charles on 2018/6/20.
 */
public class ManageWebAppConfig extends JFinalConfig{
    Log log = Log.getLog(ManageWebAppConfig.class);

    @Override
    public void configConstant(com.jfinal.config.Constants me) {
        PropKit.use("config.properties");
//        loadPropertyFile("config.properties");

        me.setDevMode(PropKit.getBoolean("run.log",true));
        me.setBaseUploadPath(GlobalConfig.file_upload_path);
        me.setJsonFactory(MyJsonFactory.me());
        me.setEncoding("UTF-8");
    }

    @Override
    public void configRoute(Routes me) {
        me.scan("cn.zhqr.manage.controller");
    }

    @Override
    public void configEngine(Engine engine) {

    }

    @Override
    public void configPlugin(Plugins me) {
        configJdbcPlugin(me);

        //启用mongo插件
        if(PropUtil.exist("mongo.properties")){
            Prop mongo = PropKit.use("mongo.properties");
            MongoPlugin mongoPlugin = new MongoPlugin(mongo.get("mongo.host"),mongo.getInt("mongo.port", 27017));
            mongoPlugin.auth(mongo.get("mongo.username"), mongo.get("mongo.password"), mongo.get("mongo.database"));
            me.add(mongoPlugin);
        }


        //启用redis插件
        if(StrKit.notBlank(PropKit.get("redis.host"))){
            RedisPlugin redisPlugin = new RedisPlugin("brand_rank", PropKit.get("redis.host"),
                    PropKit.getInt("redis.port", Protocol.DEFAULT_PORT),
                    PropKit.getInt("redis.timeout", Protocol.DEFAULT_TIMEOUT),
                    PropKit.get("redis.password"));
            redisPlugin.setSerializer(RedisStringSerializer.me); // 需要使用fst高性能序列化的用户请删除这一行（Fst jar依赖请查看WIKI）
            me.add(redisPlugin);
        }


        //启用定时任务插件
        if(PropUtil.exist("quartz_jobs.properties")){
            QuartzPlugin quartz = new QuartzPlugin("quartz_jobs.properties");
            me.add(quartz);
        }


        int processorNum = Runtime.getRuntime().availableProcessors();
        log.info("可用处理器个数  "+processorNum);
        if(processorNum>1){
            //MQTT客户端启动
            MqttAsyncClientKit.connect(null);
        }else{
            //MQTT客户端启动
            MqttClientKit.connect();
        }
    }

    private void configJdbcPlugin(Plugins me) {
        Prop jdbc = PropKit.use("jdbc.properties");
        C3p0Plugin c3p0Plugin = new C3p0Plugin(
                jdbc.get("jdbc.url"), jdbc.get("jdbc.user"),
                jdbc.get("jdbc.password").trim(), jdbc.get("jdbc.driver"));
        me.add(c3p0Plugin);

        AutoTableBindPlugin arp = new AutoTableBindPlugin(GlobalConstants.MAIN_DB, c3p0Plugin);
        arp.setShowSql(JFinal.me().getConstants().getDevMode());
        arp.autoScan(false);
        arp.addIncludePaths("cn.zhqr.db.model");//指定要扫描的package
        arp.setDialect(new MysqlDialect());
        me.add(arp);
    }

    @Override
    public void configInterceptor(Interceptors me) {
        me.add(new UncaughtExceptionInterceptor());
        CorsInterceptor corsInterceptor = new CorsInterceptor();
        if(GlobalConfig.serverMode == GlobalConstants.SERVER_MODE_PRO){
            //正式环境会通过nginx写入响应头信息，这里不再重复写入
            corsInterceptor.setWriteHeader(false);
        }
        me.add(corsInterceptor);

        me.add(new ManageLoginInterceptor());
        me.add(new PermInterceptor());
        me.add(new PreventRepeatSubmissionInterceptor());
    }

    @Override
    public void configHandler(Handlers me) {

    }

    @Override
    public void afterJFinalStart() {
        log.info(PropKit.get("app.cn.name")+"启动成功");
    }
}
